package thread;

import java.util.concurrent.Semaphore;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-10-10
 * Time: 16:50
 */
//编写代码实现两个线程增加同一个变量
//使用 Semphore 来控制线程安全.
public class Demo19 {
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);

        for(int i = 0; i < 50; i++){
            Thread thread1 = new Thread(() -> {
                try {
                    semaphore.acquire();
                    count++;
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });

            Thread thread2 = new Thread(() -> {
                try {
                    semaphore.acquire();
                    count++;
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            thread1.start();
            thread2.start();

            thread1.join();
            thread2.join();
        }
        System.out.println(count);
    }
}
